// store/index.js - Vuex状态管理
import Vue from 'vue'
import Vuex from 'vuex'
import request from '@/common/request.js'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
      // 活动类型数据
      activityTypes: [],
  selectedShop: null,
      // 全局配置数据
      config: {
      site_name: '',
      site_name_en: '',
      site_url: '',
      gaode_key: '',
      // 其他配置项...
    },
    // 用户位置信息
    location: {
      latitude: null,
      longitude: null,
      city: '',
      address: ''
    },
    // 组队信息
    teamInfo: null,
    // 用户信息
    userInfo: {
      isLogin: false,
      token: '',
      // 其他用户信息...
    },
    // 应用状态
    appStatus: {
      isLoading: false,
      networkStatus: true
    },
    // 订单相关数据
    order: {
      orderData: null,
      shopInfo: null,
      roomInfo: null,
      timeSlots: null,
      selectedCoupon: null,
      originalPrice: 0,
      roomId: '',
      shopId: '',
      availableCoupons: [],
      userBalance: 0,
      selectedPayment: 'wechat'
    }
  },

  getters: {
    // 获取配置信息
    getConfig: state => state.config,

    // 获取组队信息
    getTeamInfo: state => state.teamInfo,

    // 获取高德地图key
    getGaodeKey: state => state.config.gaode_key,

    // 获取站点名称
    getSiteName: state => state.config.site_name,

    // 获取活动类型数据
    getActivityTypes: state => state.activityTypes,

    // 获取位置信息
    getLocation: state => state.location,

    // 检查是否已登录
    isLoggedIn: state => state.userInfo.isLogin,

    // 获取用户信息
    getUserInfo: state => state.userInfo,
    // 获取用户token
    getUserToken: state => state.userInfo.token,

    // 获取订单相关数据
    getOrderData: state => state.order.orderData,
    getShopInfo: state => state.order.shopInfo,
    getRoomInfo: state => state.order.roomInfo,
    getTimeSlots: state => state.order.timeSlots,
    getSelectedCoupon: state => state.order.selectedCoupon,
    getOriginalPrice: state => state.order.originalPrice,
    getUserBalance: state => state.order.userBalance,
    getSelectedPayment: state => state.order.selectedPayment,
    getSelectedShop: state => state.selectedShop
  },

  mutations: {
    // 设置配置信息
    SET_CONFIG(state, config) {
      state.config = {
        ...state.config,
        ...config
      }
    },

    // 设置组队信息
    SET_TEAM_INFO(state, teamInfo) {
      state.teamInfo = teamInfo;
    },

    // 清除组队信息
    CLEAR_TEAM_INFO(state) {
      state.teamInfo = null;
    },

    // 设置位置信息
    SET_LOCATION(state, location) {
      state.location = {
        ...state.location,
        ...location,
        cityId: location.cityId || '',
        cityName: location.cityName || ''
      }
    },

    // 设置用户信息
    SET_USER_INFO(state, userInfo) {
      state.userInfo = {
        ...state.userInfo,
        ...userInfo
      };
      // 兼容user_coupon_count
      if (userInfo.user_coupon_count !== undefined) {
        state.userInfo.user_coupon_count = userInfo.user_coupon_count;
      }
    },

    // 设置登录状态
    SET_LOGIN_STATUS(state, status) {
      state.userInfo.isLogin = status
    },

    // 设置加载状态
    SET_LOADING(state, loading) {
      state.appStatus.isLoading = loading
    },

    // 设置网络状态
    SET_NETWORK_STATUS(state, status) {
      state.appStatus.networkStatus = status
    },

    // 设置活动类型数据
    SET_ACTIVITY_TYPES(state, types) {
      state.activityTypes = types
    },

    // 清除用户数据
    CLEAR_USER_DATA(state) {
      state.userInfo = {
        isLogin: false,
        token: '',
      }
    },

    // 订单相关 mutations
    SET_ORDER_DATA(state, data) {
      Object.keys(data).forEach(key => {
        if (state.order.hasOwnProperty(key)) {
          state.order[key] = data[key]
        }
      })
    },

    SET_SELECTED_COUPON(state, coupon) {
      state.order.selectedCoupon = coupon
    },

    CLEAR_ORDER_DATA(state) {
      state.order = {
        orderData: null,
        shopInfo: null,
        roomInfo: null,
        timeSlots: null,
        selectedCoupon: null,
        originalPrice: 0,
        roomId: '',
        shopId: '',
        availableCoupons: [],
        userBalance: 0,
        selectedPayment: 'wechat'
      }
    },
    setSelectedShop(state, shop) {
      state.selectedShop = shop;
    },
    clearSelectedShop(state) {
      state.selectedShop = null;
    }
  },

  actions: {
    // 获取并设置配置信息
    async fetchConfig({
      commit
    }) {
      try {
        commit('SET_LOADING', true)

        const {
          data: res
        } = await request.httpRequest({
          url: '/api/index/getConfig',
          method: 'get'
        });

        if (res.code === 1) {
          commit('SET_CONFIG', res.data);

          // 将配置保存到本地存储
          uni.setStorageSync('config', JSON.stringify(res.data))

          return res.data
        } else {
          throw new Error('获取配置失败')
        }
      } catch (error) {
        // 尝试从本地存储获取配置
        const localConfig = uni.getStorageSync('config')
        if (localConfig) {
          commit('SET_CONFIG', JSON.parse(localConfig))
        }

        throw error
      } finally {
        commit('SET_LOADING', false)
      }
    },

    // 获取位置信息
    async fetchLocation({ commit, state }) {
      return new Promise((resolve, reject) => {
        console.log('[定位调试] 1. 开始获取地理位置...');
        console.log('[定位调试] 2. 当前使用的高德Key:', state.config.gaode_key || '未找到Key!');

        uni.getLocation({
          type: 'gcj02',
          success: async (res) => {
            console.log('[定位调试] 3. uni.getLocation 成功:', res);
            const locationData = {
              latitude: res.latitude,
              longitude: res.longitude
            };
            commit('SET_LOCATION', locationData);
            
            if (state.config.gaode_key) {
              try {
                console.log('[定位调试] 4. 开始逆地理编码...');
                const cityInfo = await this.dispatch('reverseGeocode', {
                  latitude: res.latitude,
                  longitude: res.longitude
                });
                console.log('[定位调试] 5. 逆地理编码成功:', cityInfo);
                commit('SET_LOCATION', { ...locationData, ...cityInfo });
              } catch (error) {
                console.error('[定位调试] X. 逆地理编码失败! Error:', error);
                commit('SET_LOCATION', { ...locationData, city: '定位失败' });
              }
            } else {
               console.warn('[定位调试] X. 缺少高德地图Key，无法进行逆地理编码。');
               commit('SET_LOCATION', { ...locationData, city: '配置缺失' });
            }
            resolve(state.location);
          },
          fail: (error) => {
            console.error('[定位调试] X. uni.getLocation 失败! Error:', error);
            commit('SET_LOCATION', { city: '定位失败' });
            resolve(state.location);
          }
        });
      });
    },

    // 逆地理编码
    async reverseGeocode({ state }, { latitude, longitude }) {
      return new Promise((resolve, reject) => {
        if (!state.config.gaode_key) {
          return reject(new Error('缺少高德地图key'));
        }

        uni.request({
          url: 'https://restapi.amap.com/v3/geocode/regeo',
          data: {
            key: state.config.gaode_key,
            location: `${longitude},${latitude}`
          },
          success: (res) => {
            if (res.data.status === '1') {
              const addressComponent = res.data.regeocode.addressComponent;
              const cityInfo = {
                city: typeof addressComponent.city === 'string' && addressComponent.city.length > 0 ? addressComponent.city : addressComponent.province,
                address: res.data.regeocode.formatted_address
              };
              resolve(cityInfo);
            } else {
              console.error('[定位调试] X. 高德API返回错误:', res.data);
              reject(new Error(`逆地理编码API错误: ${res.data.info}`));
            }
          },
          fail: (err) => {
            console.error('[定位调试] X. uni.request 网络请求失败:', err);
            reject(err);
          }
        });
      });
    },

    // 用户登录
    async login({
      commit
    }, loginData) {
      try {
        commit('SET_USER_INFO', loginData)
        commit('SET_LOGIN_STATUS', true)

        // 保存到本地存储
        uni.setStorageSync('user_info', JSON.stringify(loginData)) // 添加JSON.stringify
        uni.setStorageSync('token', loginData.token) // 修正键名

        return loginData
      } catch (error) {
        throw error
      }
    },

    // 用户登出
    async logout({
      commit
    }) {
      commit('CLEAR_USER_DATA')

      // 清除本地存储
      uni.removeStorageSync('user_info')
      uni.removeStorageSync('user_token')
    },

    // 初始化应用数据
    async initApp({
      dispatch,
      commit
    }) {
      try {
        // 从本地存储恢复用户信息
        const userInfo = uni.getStorageSync('user_info')
        const userToken = uni.getStorageSync('token')
    
        if (userInfo && userToken) {
          try {
            const parsedUserInfo = JSON.parse(userInfo);
            commit('SET_USER_INFO', {
              ...parsedUserInfo,
              token: userToken
            })
            commit('SET_LOGIN_STATUS', true)
          } catch (e) {
            console.error('解析用户信息失败', e);
            // 清除无效的用户信息
            uni.removeStorageSync('user_info');
            uni.removeStorageSync('token');
          }
        }

        // 获取配置信息
        await dispatch('fetchConfig')

        // 获取位置信息
        await dispatch('fetchLocation')
      } catch (error) {}
    },

    // 订单相关 actions
    saveOrderData({
      commit
    }, data) {
      commit('SET_ORDER_DATA', data)
    },

    updateSelectedCoupon({
      commit
    }, coupon) {
      commit('SET_SELECTED_COUPON', coupon)
    },

    clearOrderData({
      commit
    }) {
      commit('CLEAR_ORDER_DATA')
    },

    // 获取最新用户信息并更新全局状态
    async fetchUserInfoAction({
      commit
    }) {
      try {
        const result = await request.httpTokenRequest({
          url: '/api/user/getPersonalCenter',
          method: 'get'
        });
        if (result.data.code === 1 && result.data.data) {
          
          // 1. 精准解析返回的数据
          const { user_info, user_coupon_count, ...otherPageData } = result.data.data;

          // 2. 构造一个纯净的、用于全局存储的 userInfo 对象
          const completeUserInfo = {
            ...(user_info || {}), // 使用展开运算符并提供默认空对象防止出错
            user_coupon_count: user_coupon_count || 0, // 确保数量存在
            token: state.userInfo.token // 保留现有token
          };
          
          // 提交核心用户信息到 store
          commit('SET_USER_INFO', completeUserInfo);
          commit('SET_LOGIN_STATUS', true);
          // 更新本地存储的用户信息
          uni.setStorageSync('user_info', JSON.stringify(completeUserInfo));
          uni.setStorageSync('token', completeUserInfo.token);
          
          // 3. 返回完整的页面数据，供 me.vue 页面使用
          return result.data.data;
          
        } else {
          throw new Error(result.data.msg || '获取用户信息失败');
        }
      } catch (error) {
        // 获取用户信息失败，保留登录状态但记录错误
        console.error('fetchUserInfoAction 失败:', error);
        return Promise.reject(error);
      }
    }
  }
})

export default store